package com.jinxin.phonecloudmusic.myapplication.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import com.jinxin.phonecloudmusic.myapplication.app.JxscApp;
import com.jinxin.phonecloudmusic.myapplication.entity.GroupBean.Play;
import com.jinxin.phonecloudmusic.myapplication.entity.MusicBean.SongList;
import com.jinxin.phonecloudmusic.myapplication.event.MusicControlEvent;
import com.jinxin.phonecloudmusic.myapplication.utils.RxBus;
import com.jinxin.phonecloudmusic.myapplication.view.IMusicProgress;
import com.litesuits.orm.db.assit.QueryBuilder;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;

/**
 * Created by ZJ on 2017/9/28 0028.
 * 控制音乐的服务
 */

public class CloudMusicService extends Service {
    private MediaPlayer mMediaPlayer;

    private int sum = 0;//总时长 单位毫秒
    private int current;

    private int prass;
    private int progress;

    private Uri uri;
    ExecutorService exec;
    private boolean contrl=false;

    @Override
    public void onCreate() {
        super.onCreate();
        exec = Executors.newSingleThreadExecutor();//单一线程，服务不在可主动释放

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        exec.execute(new Runnable() {
            @Override
            public void run() {

            }
        });
        RxBus.getDefault().register(MusicControlEvent.class).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<MusicControlEvent>() {
            @Override
            public void accept(MusicControlEvent event) throws Exception {
                if ((event.getTag()) == 0) {//0:播放包括上下首
                    internetMusicPlay((Context) event.getObj1(), (String) event.getObj2());

                }else if ((event.getTag())==1){//1:播放本地音乐包括上下首
                    //拼字符串与本地进行比较

                }else if ((event.getTag())==2){//2:暂停
                    stopMusic();
                }else if ((event.getTag())==3){//3:对暂停中的音乐进行播放
                    playAgain();
                }else if ((event.getTag())==4){//4:音量控制

                }else if ((event.getTag())==5){//5:播放进度控制（得到播放进度）
                    if (0==(int) event.getObj1()){//滑动seekbar
                        contrl=true;
                        progress= (int) event.getObj2();
                        playProgress();
                    }else{//播放歌曲，自动更新seekbar
                        contrl=false;
                        playProgress();
                    }

                }else if ((event.getTag())==6){//6:下载音乐到本地
                    String songUrl=((Play)event.getObj1()).getBitrate().getFile_link();
                    String songTitle=((Play)event.getObj1()).getSongInfo().getTitle();
                    String songAuthor=((Play)event.getObj1()).getSongInfo().getAuthor();
                    //必须要先调用播放接口，然后再调用下载方法
                    if (null!=songUrl&&null!=songTitle){
                        downLoadMusic(songUrl,songTitle,songAuthor);
                    }
                }else if ((event.getTag())==8){//快进/快退
                    /*progress= (int) event.getObj1();
                    mMediaPlayer.seekTo(progress); //seekTo方法接收的单位是:毫秒*/
                }
            }
        });
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    //播放音乐（在线音乐）和上下首功能
    private void internetMusicPlay(Context context, String url) {
        //uri = Uri.parse(play.getBitrate().getFile_link());
        //String url1 = "http://zhangmenshiting.baidu.com/data2/music/060d4777a43b6d0f0a1f7d903958020a/522932957/522932957.mp3?xcode=a33a5bb3a6a7b8a7e61345ed80ef9cd2";
        uri = Uri.parse(url);
        if (mMediaPlayer != null) {
            try {//播放完释放资源，主动置空
                if (mMediaPlayer.isPlaying()) {//如果当前正在播放音乐，这时要播放下一首，就先停止
                    mMediaPlayer.stop();
                }
                mMediaPlayer.release();
                mMediaPlayer = null;
            } catch (Exception e) {
                mMediaPlayer = null;
            }
        }
        if (mMediaPlayer == null && uri != null) {
            mMediaPlayer = MediaPlayer.create(context, uri);
            mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    if (mMediaPlayer != null) {
                        try {
                            mMediaPlayer.start();

                        } catch (Exception e) {

                        }
                    }
                }
            });
        }
    }

    //播放本地音乐
    private void localMusicPlay(String localAddress) {
        //播放本地音乐
        if (mMediaPlayer != null) {
            mMediaPlayer.stop();
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
        mMediaPlayer = new MediaPlayer();
        try {
            //设置播放源 ，当然还有其他的重载方法 eg：setDataSource(String path) path可以使网络路径也可以是本地路径，网络的记得加权限
            mMediaPlayer.setDataSource(localAddress);
            mMediaPlayer.prepareAsync();//MediaPlayer 开始准备  异步的, 还有prepare()这个是同步的
            mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    if (mMediaPlayer != null) {
                        try {
                            mMediaPlayer.start();
                            Log.e("----正在播放本地2", "hhashdhasd");
                        } catch (Exception e) {

                        }
                    }
                }
            });
            mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {//播放完毕
                    RxBus.getDefault().post(new MusicControlEvent(11,"","",""));
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            //Log.e(TAG, "设置播放源异常");
        }
    }

    //暂停
    private void stopMusic() {
        if (mMediaPlayer != null) {
            if (mMediaPlayer.isPlaying()) {
                mMediaPlayer.pause();//停止播放
            }
        }
    }

    //对暂停中的音乐进行播放
    private void playAgain() {
        if (mMediaPlayer != null) {
            try {
                mMediaPlayer.start();
            } catch (Exception e) {

            }
        }
    }

    //音量控制
    private void voiceControl(){
        //音量
        /*audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        vsVolumeSeekbar.setMax(maxVolume);
        currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        vsVolumeSeekbar.setProgress(currentVolume);*/
    }


    //播放进度控制
    private void playProgress(){
        try {
            if (mMediaPlayer != null /*&& mMediaPlayer.isPlaying()*/) {
                if (contrl==true){
                    mMediaPlayer.seekTo(progress); //seekTo方法接收的单位是:毫秒
                    sum = mMediaPlayer.getDuration();
                    current = progress;
                    RxBus.getDefault().post(new MusicControlEvent(7, sum, current,""));
                }else {
                    sum = mMediaPlayer.getDuration();
                    current = mMediaPlayer.getCurrentPosition();
                    RxBus.getDefault().post(new MusicControlEvent(7, sum, current,""));
                }
            }
        } catch (Exception e) {
            mMediaPlayer = null;
        }
    }

    //下载音乐到本地
    private void downLoadMusic(final String strUrl, final String title,final String author) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.e("------", "正在下载");
                //ToastUtil.showShort(JxscApp.getContext(), "正在下载，请稍候");
                //点击下载，设置downLrc的值为true，请求歌词，并且把请求到的歌词保存到数据库
                // downLrc = true;
                //获取歌词
                //requestLyrics("lry", play.getSongInfo().getSong_id());
                //String urlStr="http://zhangmenshiting.baidu.com/data2/music/1331d7cacaba250d57fbf2b2cad210ab/46730145/46730145.mp3?xcode=06aa8af25b6c14512b8f63f9ac723f36";
                //String urlStr = play.getBitrate().getFile_link();
                String path = "file";
                //String fileName = play.getSongInfo().getTitle() + ".mp3";
                String fileName = title +"-"+author+ ".mp3";
                OutputStream output = null;
                try {
                /*
                 * 通过URL取得HttpURLConnection
                 * 要网络连接成功，需在AndroidMainfest.xml中进行权限配置
                 * <uses-permission android:name="android.permission.INTERNET" />
                 */
                    URL url = new URL(strUrl);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    //取得inputStream，并将流中的信息写入SDCard
                /*
                 * 写前准备
                 * 1.在AndroidMainfest.xml中进行权限配置
                 * <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
                 * 取得写入SDCard的权限
                 * 2.取得SDCard的路径： Environment.getExternalStorageDirectory()
                 * 3.检查要保存的文件上是否已经存在
                 * 4.不存在，新建文件夹，新建文件
                 * 5.将input流中的信息写入SDCard
                 * 6.关闭流
                 */
                    String SDCard = Environment.getExternalStorageDirectory() + "";
                    String pathName = SDCard + "/" + path + "/" + fileName;//文件存储路径

                    File file = new File(pathName);

                    InputStream input = conn.getInputStream();
                    if (file.exists()) {
                        System.out.println("exits");
                        return;
                    } else {
                        String dir = SDCard + "/" + path;
                        new File(dir).mkdir();//新建文件夹
                        file.createNewFile();//新建文件
                        output = new FileOutputStream(file);
                        //读取大文件
                        byte[] buffer = new byte[4*1024];
                        int len = input.read(buffer);
                        while (len != -1) {
                            output.write(buffer,0,len);
                            len = input.read(buffer);

                        }
                        output.flush();
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (output != null) {
                            output.close();
                        }
                        Log.e("------", "mp3文件下载成功");
                        System.out.println("success");
                    } catch (IOException e) {
                        System.out.println("fail");
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    //下载歌词到本地
    private void requestLyrics(){

    }

    @Override
    public void onDestroy() {
        exec.shutdown();//销毁线程
        RxBus.getDefault().unregisterAll();
        super.onDestroy();
    }


}
